import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Select, 
  Button, 
  Card, 
  message, 
  Upload, 
  Row, 
  Col,
  Spin,
  List,
  Typography
} from 'antd';
import { 
  SaveOutlined, 
  UploadOutlined, 
  CustomerServiceOutlined, 
  BugOutlined,
  FileOutlined,
  DeleteOutlined 
} from '@ant-design/icons';
import { useHistory, useParams } from 'react-router-dom';
import api from '../services/api';

const { TextArea } = Input;
const { Option } = Select;
const { Text } = Typography;

const IssueEditPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fetchLoading, setFetchLoading] = useState(true);
  const [fileList, setFileList] = useState([]);
  const [existingAttachments, setExistingAttachments] = useState([]);
  const history = useHistory();
  const { id } = useParams();

  // 获取问题详情
  const fetchIssueDetail = async () => {
    setFetchLoading(true);
    try {
      const response = await api.get(`/issues/${id}`);
      const issue = response.data;
      
      // 设置表单值
      form.setFieldsValue({
        title: issue.title,
        description: issue.description,
        type: issue.type,
        category: issue.category,
        priority: issue.priority,
        related_case: issue.matched_case_id
      });
      
      // 设置现有附件
      if (issue.attachments) {
        setExistingAttachments(issue.attachments);
      }
    } catch (error) {
      console.error('获取问题详情失败:', error);
      
      // 如果错误已经被拦截器处理过，则不再显示错误消息
      if (!error.handled) {
        message.error('获取问题详情失败');
      }
    } finally {
      setFetchLoading(false);
    }
  };

  useEffect(() => {
    fetchIssueDetail();
  }, [id]);

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      // 准备请求数据
      const issueData = {
        title: values.title,
        description: values.description,
        type: values.type,
        category: values.category,
        priority: values.priority
      };
      
      // 如果有关联案例，添加到数据中
      if (values.related_case) {
        issueData.matched_case_id = values.related_case;
      }
      
      // 1. 先更新问题基本信息
      const response = await api.put(`/issues/${id}`, issueData);
      console.log('更新问题成功:', response.data);
      
      // 2. 上传新附件
      if (fileList && fileList.length > 0) {
        console.log('开始上传附件:', fileList);
        
        for (const fileItem of fileList) {
          if (fileItem.originFileObj) {
            const formData = new FormData();
            formData.append('file', fileItem.originFileObj);
            formData.append('entity_type', 'issue');
            formData.append('entity_id', id);
            
            try {
              const uploadResponse = await api.post('/attachments/upload', formData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                },
              });
              console.log('附件上传成功:', uploadResponse.data);
            } catch (uploadError) {
              console.error('附件上传失败:', uploadError);
              message.warning(`附件 "${fileItem.name}" 上传失败`);
            }
          }
        }
      }
      
      message.success('问题更新成功');
      history.push(`/issues/${id}`);
    } catch (error) {
      console.error('问题更新失败:', error);
      
      // 如果错误已经被拦截器处理过（如401认证错误），则不再显示错误消息
      if (error.handled) {
        return;
      }
      
      if (error.response) {
        const errorMessage = error.response.data?.detail || '问题更新失败，请稍后重试';
        message.error(errorMessage);
      } else if (error.request) {
        message.error('网络错误，请检查网络连接');
      } else {
        message.error('问题更新失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    history.push(`/issues/${id}`);
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const handleUpload = ({ file, fileList }) => {
    setFileList(fileList);
    return false; // 阻止自动上传
  };

  const handleDeleteAttachment = async (attachmentId) => {
    try {
      await api.delete(`/issues/${id}/attachments/${attachmentId}`);
      message.success('附件删除成功');
      
      // 更新现有附件列表
      setExistingAttachments(prev => prev.filter(att => att.id !== attachmentId));
    } catch (error) {
      console.error('删除附件失败:', error);
      
      // 如果错误已经被拦截器处理过，则不再显示错误消息
      if (!error.handled) {
        message.error('删除附件失败');
      }
    }
  };

  if (fetchLoading) {
    return <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />;
  }

  return (
    <div>
      <h2>编辑问题</h2>
      
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="问题标题"
                rules={[{ required: true, message: '请输入问题标题' }]}
              >
                <Input placeholder="简要描述问题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="问题类型"
                rules={[{ required: true, message: '请选择问题类型' }]}
              >
                <Select>
                  <Option value="customer">
                    <CustomerServiceOutlined /> 客户问题
                  </Option>
                  <Option value="internal">
                    <BugOutlined /> 内部问题
                  </Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="问题描述"
            rules={[{ required: true, message: '请输入问题详细描述' }]}
          >
            <TextArea 
              rows={6} 
              placeholder="请详细描述问题现象、复现步骤、环境信息等" 
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="问题分类"
                rules={[{ required: true, message: '请选择问题分类' }]}
              >
                <Select>
                  <Option value="hardware">硬件</Option>
                  <Option value="software">软件</Option>
                  <Option value="firmware">固件</Option>
                  <Option value="network">网络</Option>
                  <Option value="other">其他</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select>
                  <Option value="low">低</Option>
                  <Option value="medium">中</Option>
                  <Option value="high">高</Option>
                  <Option value="urgent">紧急</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="related_case"
                label="关联案例"
              >
                <Select
                  showSearch
                  placeholder="搜索关联案例"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="1">设备无法启动</Option>
                  <Option value="2">软件界面无响应</Option>
                  <Option value="3">网络连接不稳定</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          {/* 现有附件显示 */}
          {existingAttachments.length > 0 && (
            <Form.Item label="现有附件">
              <List
                size="small"
                dataSource={existingAttachments}
                renderItem={(item) => (
                  <List.Item
                    actions={[
                      <Button
                        type="link"
                        icon={<DeleteOutlined />}
                        danger
                        onClick={() => handleDeleteAttachment(item.id)}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<FileOutlined />}
                      title={item.filename || '附件文件'}
                      description={
                        <Text type="secondary">
                          {item.file_size ? `大小: ${(item.file_size / 1024).toFixed(2)} KB` : ''}
                        </Text>
                      }
                    />
                  </List.Item>
                )}
              />
            </Form.Item>
          )}

          {/* 新增附件上传 */}
          <Form.Item
            name="attachments"
            label="新增附件"
            valuePropName="fileList"
            getValueFromEvent={normFile}
          >
            <Upload 
              name="attachments" 
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={() => false} // 阻止自动上传
            >
              <Button icon={<UploadOutlined />}>点击上传新附件</Button>
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading} 
              icon={<SaveOutlined />}
            >
              保存更改
            </Button>
            <Button 
              style={{ marginLeft: 8 }}
              onClick={handleCancel}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default IssueEditPage;